package com.yztc.youbadbad.ui.other.fragment;


import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.tiffany.greendao.DaoSession;
import com.tiffany.greendao.ProductDao;
import com.yztc.youbadbad.App;
import com.yztc.youbadbad.R;
import com.yztc.youbadbad.adapter.ShoppingCarAdapter;
import com.yztc.youbadbad.bean.homepage.ProductBean;
import com.yztc.youbadbad.utils.ToastUtils;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.bmob.v3.BmobBatch;
import cn.bmob.v3.BmobObject;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.datatype.BatchResult;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.QueryListListener;

/**
 * A simple {@link Fragment} subclass.
 */
public class ShoppingcarFragment extends Fragment implements ShoppingCarAdapter.IItemCheckedboxChange {
    @BindView(R.id.shopping_car_editor)
    Button shoppingCarEditor;
    @BindView(R.id.shoppingcar_listview)
    ListView shoppingcarListview;
    @BindView(R.id.shoppingcar_emptyview)
    TextView shoppingcarEmptyview;//空view
    @BindView(R.id.progressBar)
    ProgressBar progressBar;
    @BindView(R.id.total)
    TextView total;
    @BindView(R.id.footer_button)
    Button footerButton;
    @BindView(R.id.footer)
    RelativeLayout footer;

    private Context mContext = App.app;
    private DaoSession daoSession = App.newInstance().getDaoSession();
    private ProductDao productDao;
    //private List<Product> mProductList = new ArrayList<>();
    private List<ProductBean> mProductList = new ArrayList<>();
    private ShoppingCarAdapter shoppingCarAdapter;
    private CheckBox mCheckhead;
    private boolean flag;
    private View headView;
    private BmobQuery<ProductBean> bmobQuery;
    private double money;
    private int totalCount;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_shoppingcar, container, false);
        ButterKnife.bind(this, view);
        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initView();
        initData();
    }

    private void initData() {
       /*/productDao = daoSession.getProductDao();
        List<Product> list = productDao.queryBuilder().list();*/
        bmobQuery = new BmobQuery<ProductBean>();
        bmobQuery.findObjects(new FindListener<ProductBean>() {
            @Override
            public void done(List<ProductBean> list, BmobException e) {
                if (list != null && list.size() < 0) {
                    shoppingcarListview.removeHeaderView(headView);
                    progressBar.setVisibility(View.GONE);
                } else {
                    for (int i = 0; i < list.size(); i++) {
                        list.get(i).setCheck(true);
                    }
                    shoppingCarAdapter.reloadListView(list, true);
                    editChange();
                    progressBar.setVisibility(View.GONE);
                }
            }
        });

    }

    private void initView() {
        LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        headView = inflater.inflate(R.layout.headview_shoppingcar, null);//headview
        mCheckhead = (CheckBox) headView.findViewById(R.id.checkbox_head);//checkbox
        mCheckhead.setChecked(true);

        mCheckhead.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked == false) {
                    total.setText("总计：￥ 0.00");
                    footerButton.setText("去结算（0)");
                } else if(shoppingCarEditor.getText().equals("完成")){

                }else {
                    total.setText("总计：￥ " + String.format("%.2f", money));
                    footerButton.setText("去结算（" + totalCount + ")");
                }
                for (int i = 0; i < mProductList.size(); i++) {
                    mProductList.get(i).setCheck(isChecked);
                    shoppingCarAdapter.notifyDataSetChanged();
                }
            }
        });
        shoppingcarListview.setEmptyView(shoppingcarEmptyview);//空
        shoppingcarListview.addHeaderView(headView);
        shoppingCarAdapter = new ShoppingCarAdapter(mContext, mProductList, this);
        shoppingcarListview.setAdapter(shoppingCarAdapter);

    }

    @OnClick({R.id.shopping_car_editor, R.id.footer_button})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.shopping_car_editor://默认编辑
                editChange();
                break;
            case R.id.footer_button:
                if (footerButton.getText().equals("删除")) {//删除
                    deleteBatch();
                } else {//结算

                }
                break;
        }
    }

    /**
     * 右上角编辑完成切换
     */
    private void editChange() {
        if (!flag) {
            shoppingCarEditor.setText("编辑");
            mCheckhead.setChecked(true);
            money = 0;
            totalCount = 0;
            for (int i = 0; i < mProductList.size(); i++) {
                ProductBean productBean = mProductList.get(i);
                if (productBean.isCheck() == true) {
                    totalCount += productBean.getNum();
                    int count = 0;
                    count = productBean.getNum();
                    money += productBean.getStore_price() * count;
                }
            }

            total.setVisibility(View.VISIBLE);
            total.setText("总计：￥ " + String.format("%.2f", money));
            footerButton.setText("去结算（" + totalCount + ")");

        } else {
            shoppingCarEditor.setText("完成");
            mCheckhead.setChecked(false);

            total.setVisibility(View.GONE);
            footerButton.setText("删除");
        }
        flag = !flag;
    }

    /**
     * 删除选中项目
     */
    private void deleteBatch() {
        List<BmobObject> newList = new ArrayList<>();
        for (int i = 0; i < mProductList.size(); i++) {
            ProductBean productBean = mProductList.get(i);
            if (productBean.isCheck() == true) {
                newList.add(productBean);
                mProductList.remove(productBean);
            }
        }
        shoppingCarAdapter.notifyDataSetChanged();//刷新列表
        BmobBatch batch = new BmobBatch();//删除
        batch.deleteBatch(newList);
        //执行批量操作
        batch.doBatch(new QueryListListener<BatchResult>() {

            @Override
            public void done(List<BatchResult> results, BmobException ex) {
                if (ex == null) {
                    //返回结果的results和上面提交的顺序是一样的，请一一对应
                    for (int i = 0; i < results.size(); i++) {
                        ToastUtils.showToast(mContext, "删除成功" + results.size() + "成功");
                    }
                } else {
                    ToastUtils.showToast(mContext, "没有物品可删除");
                }
            }
        });
    }


    @Override
    public void itemCheckboxChange(int change, double price, int delete) {
        switch (change) {
            case 0://点击
                break;
            case 1://加法
                money = money + price;
                total.setText("总计：￥ " + String.format("%.2f", money));
                totalCount = (totalCount + delete);
                footerButton.setText("去结算（" + totalCount + ")");
                break;
            case 2://减法
                money = money - price;
                total.setText("总计：￥ " + String.format("%.2f", money));
                totalCount = (totalCount - delete);
                footerButton.setText("去结算（" + totalCount + ")");
                break;
        }
    }
}
